import React, { useEffect, useState, useRef, useContext } from 'react';
import { Button, Input, Table, Select } from 'antd';
import { JumpSetContext } from '../ChartPanel';
// import RichEditor from './RichEditor'

const EditableCell = ({
  editable,
  children,
  dataIndex,
  record,
  handleSave,
}) => {
  const { selectList } = useContext(JumpSetContext);
  const [editing, setEditing] = useState(false);
  const inputRef = useRef(null);
  // const insertRef = useRef(null)

  useEffect(() => {
    if (editing) {
      inputRef.current.focus();
    }
  }, [editing]);

  const toggleEdit = () => {
    setEditing(!editing);
  };

  let childNode = children;
  if (editable) {
    childNode = editing ? (
      <>
        {dataIndex === 'name' ? (
          <Input
            ref={inputRef}
            defaultValue={record[dataIndex]}
            onChange={e => {
              handleSave({ ...record, [dataIndex]: e.target.value });
            }}
            onBlur={toggleEdit}
          />
        ) : (
          <Select
            placeholder={'请选择源字段'}
            ref={inputRef}
            // value={config.list[i].sourceId}
            // size='small'
            defaultValue={record[dataIndex]}
            options={selectList}
            onChange={val => {
              handleSave({ ...record, [dataIndex]: val });
            }}
            onBlur={toggleEdit}
            style={{ width: '100%' }}
          />
        )}
      </>
    ) : (
      <>
        {dataIndex === 'name' ? (
          <div
            className="editable-cell-value-wrap"
            style={{ paddingRight: 24, height: '24px',cursor:'pointer' }}
            onClick={toggleEdit}
          >
            {record[dataIndex]}
          </div>
        ) : (
          <div
            className="editable-cell-value-wrap"
            style={{ paddingRight: 24, height: '24px',cursor:'pointer'   }}
            onClick={toggleEdit}
          >
            {selectList.find(item=>item.value===record[dataIndex])?.label}
          </div>
        )}
      </>
    );
  }

  return <td>{childNode}</td>;
};

const WebUrl = ({ config, onchange }) => {
  let initQureyString = (config.jumpUrl || '').split('?')[1] || '';
  let initQureyList = [];
  if (initQureyString) {
    initQureyString
      .split('&')
      .map(item => item.split('='))
      .forEach((item, i) =>
        initQureyList.push({
          key: `${i}`,
          name: item[0] || '',
          value: item[1] || '',
        }),
      );
    initQureyList.push({ key: `${initQureyList.length}`, name: '', value: '' });
  } else {
    initQureyList.push({ key: `0`, name: '', value: '' });
  }

  const [urlValue, setUrlValue] = useState(config.jumpUrl || '');
  const [queryList, setQueryList] = useState(initQureyList);
  const [count, setCount] = useState(initQureyList.length - 1);

  useEffect(() => {
    onchange({ jumpUrl: urlValue });
  }, [urlValue]);

  const inputChange = e => {
    const val = e.target.value;
    setUrlValue(val);
    let list = val.split('?')[1];
    if (list) {
      list = list
        .split('&')
        .map(item => item.split('='))
        .map((item, i) => ({
          key: `${i}`,
          name: item[0] || '',
          value: item[1] || '',
        }));
      setCount(list.length);
      list.push({ key: `${list.length}`, name: '', value: '' });
    } else {
      list = [{ key: `0`, name: '', value: '' }];
    }
    setQueryList(list);
  };
  const handleSave = row => {
    const newData = [...queryList];
    const index = newData.findIndex(item => row.key === item.key);
    const item = newData[index];
    newData.splice(index, 1, {
      ...item,
      ...row,
    });
    if (newData[newData.length - 1].name) {
      setCount(pre => pre + 1);
      newData.push({ key: `${count + 1}`, name: '', value: '' });
    }
    setQueryList(newData);

    setUrlValue(pre => {
      const baseUrl = pre.split('?')[0];
      return `${baseUrl}?${newData
        .map(item => (item.name ? `${item.name}=${item.value}` : null))
        .filter(e => e)
        .join('&')}`;
    });
  };
  const defaultColumns = [
    {
      key: '0',
      title: '参数名称',
      dataIndex: 'name',
      width: '30%',
      editable: true,
    },
    {
      key: '1',
      title: '参数值',
      dataIndex: 'value',
      width: '50%',
      editable: true,
    },
    {
      key: '2',
      title: '操作',
      width: '20%',
      dataIndex: 'operate',
      render: (_, record) => (
        <Button
          type={'link'}
          onClick={() => {
            setQueryList(pre => {
              const data = pre.filter(
                (item, i) => item.key !== record.key || i === pre.length - 1,
              );
              setUrlValue(pre => {
                const baseUrl = pre.split('?')[0];
                return `${baseUrl}?${data
                  .map(item =>
                    item.name ? `${item.name}=${item.value}` : null,
                  )
                  .filter(e => e)
                  .join('&')}`;
              });
              return data;
            });
          }}
        >
          删除
        </Button>
      ),
    },
  ];
  const columns = defaultColumns.map(col => {
    if (!col.editable) {
      return col;
    }
    return {
      ...col,
      onCell: record => ({
        record,
        editable: col.editable,
        dataIndex: col.dataIndex,
        title: col.title,
        handleSave,
      }),
    };
  });
  return (
    <div style={{ margin: '0 20px',display:'flex',flexDirection:'column',height: '100%' }}>
      {/* <RichEditor insertRef={insertRef}/> */}
      {/* <Button onClick=  {()=>insertRef?.insertNode&&insertRef.insertNode('out')}>out</Button> */}
      <Input addonBefore="跳转url" value={urlValue} onChange={inputChange} />
      <Table
        style={{ marginTop: '20px',flex:1 }}
        components={{
          body: {
            cell: EditableCell,
          },
        }}
        // rowClassName={() => 'editable-row'}
        pagination={false}
        bordered
        scroll={{ x: 'auto', y: 'auto' }}
        dataSource={queryList}
        columns={columns}
      />
      {/* <div style={{ height: '35px' }}>
        打开位置{' '}
        <Select
          value={config.openType || '1'}
          onChange={openType => onchange({ openType })}
          options={[
            { label: '新窗口打开', value: '1' },
            { label: '弹框打开', value: '2' },
          ]}
        />
      </div> */}

    </div>
  );
};

export default WebUrl;
